/* eslint-disable no-param-reassign */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react/jsx-key */
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Switch, Modal, Button, Form, Popconfirm, message, Tabs, Input } from 'antd';
import { connect, useRequest } from 'umi';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { postFetch } from '@/utils/doFetch';
import { stopsettle, companydetail, company } from '@/services/business';
import { area, user, classify } from '@/services/basic';
import moment from 'moment';
import { BarcodeOutlined } from '@ant-design/icons';
import { useDebounce, useInterval } from 'ahooks';
import Mutipledit from './mutipledit';
import CompanyName from '@/components/CompanyName';

let Voucher = (props) => {
  const { global, dispatch } = props;
  let actionRef = useRef(),
    ChildRef = null;
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState({}),
    [iftype, ciftype] = useState({}),
    [formRef] = Form.useForm(),
    [key, setkey] = useState('1');
  const [selectedRowKeys, setselectedRowKeys] = useState({
    1: [],
    2: [],
  });
  const [selectedRows, setSelectedRows] = useState({
    1: [],
    2: [],
  });

  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = [
    {
      title: '业务编号',
      dataIndex: 'service_code',
      key: 'service_code',
    },
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'company_name',
      key: 'company_name',
      render: (_, row) => (
        <CompanyName
          row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
          reload={reload}
        />
      ),
    },
    {
      title: '公司类型',
      dataIndex: 'classify_name',
      key: 'classify_id',
      valueType: 'select',
      options: {
        database: classify,
        params: { is_all: 1 },
      },
    },
    {
      title: '月收费',
      dataIndex: 'unit_price',
      key: 'unit_price',
      search: false,
    },
    {
      title: '记账提成',
      dataIndex: 'account_take',
      key: 'account_take',
      ellipsis: true,
      search: false,
    },
    {
      title: '复核提成',
      dataIndex: 'review_take',
      key: 'review_take',
      ellipsis: true,
      search: false,
    },
    {
      title: '报送日期',
      dataIndex: 'submit_date',
      key: 'submit_date',
      search: false,
      render: (text, row) => {
        return (
          <span className="oneline">
            {row.submit_date ? moment(row.submit_date).format('YYYY-MM-DD') : ''}
          </span>
        );
      },
    },
    {
      title: '区域名称',
      dataIndex: 'area_name',
      key: 'area_id',
      valueType: 'select',
      options: {
        database: area,
        params: {
          is_all: 1,
        },
      },
    },
    {
      title: '记账会计',
      dataIndex: 'creator_name',
      key: 'creator_id',
      valueType: 'select',
      options: {
        database: user,
        params: {
          is_all: 1,
        },
      },
    },
    //  ” review_user_name

    {
      title: '复核会计',
      dataIndex: 'review_user_name',
      key: 'review_user_id',
      valueType: 'select',
      options: {
        database: user,
        params: {
          is_all: 1,
        },
      },
    },
    {
      title: '凭证日期',
      dataIndex: 'voucher_date',
      key: 'voucher_date',
      valueType: 'dateMonth',
    },
    {
      title: '状态',
      dataIndex: 'status_name',
      key: 'status',
      valueType: 'select',
      options: [
        {
          label: '暂存',
          value: 'cache',
        },
        {
          label: '复核中',
          value: 'pending',
        },
        {
          label: '会计主管拒绝',
          value: 'refuse',
        },
        {
          label: '审核完成',
          value: 'review',
        },
        {
          label: '归档完成',
          value: 'completed',
        },
      ],
    },
    {
      title: '备注',
      dataIndex: 'in_store_remark',
      key: 'in_store_remark',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 160,
      render: (text, row, _, action) => extraAction(text, row, _, action),
    },
  ];

  function extraAction(text, record, _, action) {
    return [
      <Popconfirm
        title="确认通过该凭证？"
        disabled={record.status != 'pending'}
        onConfirm={() => {
          dispatch({
            type: 'customer/reviewvoucher',
            payload: { ids: [record.id] },
          }).then((res) => {
            if (res.code == 0) {
              message.success('操作成功');
              reload();
              cvs(false);
            }
          });
        }}
      >
        <a disabled={record.status != 'pending'}>通过</a>
      </Popconfirm>,
      <a
        disabled={record.status != 'pending'}
        style={{ color: record.status != 'pending' ? '#ddd' : '#f50' }}
        onClick={() => {
          if (record.status != 'pending') {
            return;
          }
          cvs(true);
          cf((fields) => {
            return {
              refuse_message: {
                value: null,
                type: 'textarea',
                title: '拒绝理由',
                name: ['refuse_message'],
                required: false,
                col: { span: 24 },
              },
            };
          });
          ciftype({
            val: 'refuse',
            title: '拒绝理由',
            id: [record.id],
          });
        }}
      >
        拒绝
      </a>,
      <a
        disabled={record.status != 'review'}
        style={{ color: record.status != 'review' ? '#ddd' : '#13c2c2' }}
        onClick={() => {
          if (record.status != 'review') {
            return;
          }
          cvs(true);
          cf((fields) => {
            return {
              voucher_barcode: {
                value: null,
                type: 'scan',
                title: '凭证条码号',
                name: ['voucher_barcode'],
                required: false,
                col: { span: 24 },
              },
              in_store_remark: {
                value: null,
                type: 'textarea',
                title: '备注',
                name: ['in_store_remark'],
                required: false,
                col: { span: 24 },
              },
            };
          });
          ciftype({
            val: 'inside',
            title: '凭证入库',
            id: record.id,
          });
        }}
      >
        入库
      </a>,
    ];
  }

  let saveData = (values, fn) => {
    let { dispatch } = props;
    if (iftype.val == 'refuse') {
      dispatch({
        type: 'customer/refusevoucher',
        payload: { ...values, ids: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }

    if (iftype.val == 'inside') {
      dispatch({
        type: 'customer/vouchercomplete',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };
  const [typer, setTyper] = useState(false); //---------------------------------------------------------------- false

  const casea = useMemo(() => {
    let dom = [
      <a
        disabled={selectedRowKeys[key].length == 0}
        onClick={() => {
          if (selectedRowKeys[key].length == 0) return;
          dispatch({
            type: 'customer/reviewvoucher',
            payload: {
              ids: selectedRowKeys[key],
            },
          }).then((res) => {
            if (res.code == 0) {
              message.success('操作成功');
              reload();
              cvs(false);
              setselectedRowKeys({
                ...selectedRowKeys,
                [key]: [],
              });
            }
          });
        }}
      >
        通过
      </a>,
      <a
        disabled={selectedRowKeys[key].length == 0}
        style={{
          color: selectedRowKeys[key].length == 0 ? 'rgba(0, 0, 0, 0.25)' : 'red',
        }}
        onClick={() => {
          if (selectedRowKeys[key].length == 0) return;
          cvs(true);
          cf((fields) => {
            return {
              refuse_message: {
                value: null,
                type: 'textarea',
                title: '拒绝理由',
                name: ['refuse_message'],
                required: false,
                col: { span: 24 },
              },
            };
          });
          ciftype({
            val: 'refuse',
            title: '拒绝理由',
            id: selectedRowKeys[key],
          });
        }}
      >
        拒绝
      </a>,
    ];
    if (typer) {
      dom = [
        <a
          disabled={selectedRowKeys[key].length == 0}
          style={{
            color: selectedRowKeys[key].length == 0 ? 'rgba(0, 0, 0, 0.25)' : 'red',
            marginLeft: 12,
          }}
          onClick={() => {
            if (selectedRowKeys[key].length == 0) return;
            cvs(true);
            ciftype({
              val: 'scan',
              title: '批量入库',
            });
            setCurrent(selectedRowKeys[key][0]);
            setTimeout(() => {
              inputref?.current?.focus();
            }, 600);
          }}
        >
          批量入库
        </a>,
      ];
    }
    return dom;
  }, [typer, selectedRowKeys]);

  const [current, setCurrent] = useState(0);
  const [scan, setScan] = useState(null);
  const inputref = useRef();
  const [shown, setShown] = useState(false);
  const debouncedValue = useDebounce(scan, { wait: 800 });

  const [dao, setDao] = useState(3);
  const [int, setInt] = useState(undefined);

  useInterval(() => {
    if (dao > 0) {
      setDao((s) => s - 1);
    } else {
      setInt(null);
      setTimeout(() => {
        setShown(false);
        setDao(3);
        setScan(undefined);
      }, 100);

      if (shown) {
        dispatch({
          type: 'customer/vouchercomplete',
          payload: { voucher_barcode: scan, id: current },
        }).then((res) => {
          if (res.code == 0) {
            message.success('入库成功');
            reload();
            const nextindex = selectedRowKeys[key].indexOf(current) + 1;
            if (nextindex === selectedRowKeys[key]?.length) {
              message.info('恭喜！您已经操作到最后一条记录');
              return;
            }
            setCurrent(selectedRowKeys[key][nextindex]);
            inputref?.current?.focus();
          }
        });
      }
    }
  }, int);

  useEffect(() => {
    if (debouncedValue) {
      setShown(true);
      setInt(1000);
    }
  }, [debouncedValue]);

  const [in_store_remark, setIn_store_remark] = useState(null);

  return (
    <div className="nopa autotable">
      <AutoTable
        tabList={[
          {
            key: '1',
            tab: '正常',
          },
          {
            key: '2',
            tab: '逾期',
          },
        ]}
        onTabChange={(val) => {
          setkey(val);
        }}
        rowSelection={{
          selectedRowKeys: selectedRowKeys[key],
          preserveSelectedRowKeys: true,
          onChange: (selectedRowKeys, selectedRows) => {
            setselectedRowKeys((s) => ({ ...s, [key]: selectedRowKeys }));
            setSelectedRows((s) => ({ ...s, [key]: selectedRows }));
          },
          getCheckboxProps: (record) => ({
            disabled:
              record.status == 'completed' ||
              (typer ? record.status == 'pending' : record.status != 'pending'), // Column configuration not to be checked
          }),
        }}
        pagetitle={props.route.name}
        tabBarExtraContent={
          <div className="center" style={{ gap: 12 }}>
            <Switch
              checked={typer}
              checkedChildren="入库"
              unCheckedChildren="审批"
              onChange={(val) => {
                setselectedRowKeys((s) => ({ ...s, [key]: [] }));
                setSelectedRows((s) => ({ ...s, [key]: [] }));
                setTyper(val);
              }}
            />
            {casea}
          </div>
        }
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        extraparams={{ is_delay: key === '2' }}
        path="/wbn-api/voucher"
      />

      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => {
          cvs(false);
          setIn_store_remark(null);
        }}
        footer={
          iftype?.val === 'scan' ? (
            <Button
              type="primary"
              onClick={async () => {
                console.log(selectedRows[key]);
                if (selectedRows[key]?.some((it) => !it?.voucher_barcode)) {
                  message.warn('存在未填写的凭证条码号!');
                  return;
                }

                // 使用for循环遍历执行异步方法
                async function processItems() {
                  for (let i = 0; i < selectedRows[key].length; i++) {
                    const it = selectedRows[key][i] ?? {};
                    await dispatch({
                      type: 'customer/vouchercomplete',
                      payload: {
                        voucher_barcode: it?.voucher_barcode,
                        id: it?.id,
                        in_store_remark,
                      },
                    }).then((res) => {
                      if (res.code == 0) {
                        message.destroy();
                        message.success('操作成功');
                      } else {
                        message.destroy();
                        message.warning('操作失败');
                      }
                    });
                  }
                }

                // 调用处理函数
                await processItems();

                setSelectedRows({
                  1: [],
                  2: [],
                });
                setselectedRowKeys({
                  1: [],
                  2: [],
                });
                setIn_store_remark(null);
                reload();
                cvs(false);
              }}
            >
              批量入库
            </Button>
          ) : (
            false
          )
        }
        destroyOnClose={true}
        width={iftype?.val === 'scan' ? 1200 : 600}
      >
        {iftype?.val === 'scan' ? (
          <div style={{ position: 'relative' }}>
            <Mutipledit
              dataSource={selectedRows[key] ?? []}
              value={selectedRows[key] ?? []}
              onValuesChange={(val) => {
                setSelectedRows((s) => ({
                  ...s,
                  [key]: val,
                }));
              }}
              editable={{
                editableKeys: selectedRows?.[key]?.map?.((it) => it.id) ?? [],
              }}
            />
            <p style={{ marginTop: 24 }}>本次入库备注</p>
            <Input.TextArea
              placeholder="备注"
              value={in_store_remark}
              rows={8}
              onChange={(e) => {
                setIn_store_remark(e.target.value);
              }}
            />

            {/* <Tabs
              tabPosition="left"
              activeKey={current}
              onChange={setCurrent}
              style={{
                height: 400,
              }}
              items={selectedRows[key]?.map((it) => ({
                key: it?.id,
                label: it?.company_name,
                children: (
                  <div>
                    <p>凭证日期:{it?.voucher_date}</p>
                    <Input
                      ref={inputref}
                      prefix={<BarcodeOutlined />}
                      value={scan}
                      onChange={(e) => {
                        setScan(e.target.value);
                      }}
                      allowClear
                    />
                  </div>
                ),
              }))}
            />
            {shown && (
              <div
                className="center"
                style={{
                  flexDirection: 'column',
                  gap: 16,
                  position: 'absolute',
                  width: '100%',
                  height: '100%',
                  zIndex: 999,
                  backgroundColor: 'rgba(255,255,255,0.5)',
                  backdropFilter: 'blur(2px)',
                  top: 0,
                  left: 0,
                }}
              >
                <span>
                  倒计时: <b>{dao}</b>
                </span>
                <Button
                  onClick={() => {
                    setShown(false);
                    setInt(null);
                    setScan(undefined);
                    setDao(3);
                  }}
                >
                  重新录入
                </Button>
              </div>
            )} */}
          </div>
        ) : (
          <InitForm
            formRef={formRef}
            fields={fields}
            submitData={(values, fn) => {
              saveData(values, fn);
            }}
            onChange={(changedValues, allValues) => {}}
            submitting={
              props.loading.effects['customer/addvoucher'] ||
              props.loading.effects['customer/editvoucher'] ||
              !vs
            }
          />
        )}
      </Modal>
    </div>
  );
};

export default connect(({ global, loading }) => ({
  global,
  loading,
}))(Voucher);
